package org.redis.cluster.registry.zookeeper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.config.RegistryConfig;
import org.redis.cluster.config.SystemConfig;
import org.redis.cluster.registry.AbstractRegistry;
import org.redis.cluster.registry.Listener;
import org.redis.cluster.registry.Node;
import org.redis.cluster.registry.NodeMode;

public class ZookeeperRegistry extends AbstractRegistry {
	
	private RegistryConfig config;
	private SystemConfig systemConfig;
	private CuratorFramework client;
	private ZookeeperRegistryWatcher watcher;
	
	public ZookeeperRegistry() {
		super();
	}
	
	public ZookeeperRegistry(RegistryConfig config) {
		super(config);
		this.config=config;
	}
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.systemConfig=redisCluster.getConfigManager().getSystemConfig();
		this.client=initClient();
		this.watcher=initWatcher();
		super.init(redisCluster);
	}
	
	@Override
	public void destroy() {
		super.destroy();
		doWatcherDestroy();
	}
	
	protected ZookeeperRegistryWatcher initWatcher() {
		return new ZookeeperRegistryWatcher(client);
	}
	
	protected CuratorFramework initClient() {
		CuratorFramework curatorFramework=CuratorFrameworkFactory.builder()
				.connectString(config.getHost())
				.sessionTimeoutMs(config.getTimeout())
				.retryPolicy(new RetryNTimes(systemConfig.get(ZookeeperSystemConfigs.RETRY_COUNT).getValue(Integer.class, ZookeeperSystemConfigs.DEFAULT_RETRY_COUNT),
						config.getTimeout())).build();
		
		curatorFramework.start();
		return curatorFramework;
	}

	protected void doWatcherDestroy() {
		watcher.destroy();
	}
	
	@Override
	protected boolean doRegister(String path, Node node) throws Exception {
		if(node==null || node.getData()==null) {
			client.create().withMode(getNodeCreateMode(node)).forPath(path,ArrayUtils.EMPTY_BYTE_ARRAY);
		}
		else {
			client.create().withMode(getNodeCreateMode(node)).forPath(path,doByteSerialize(node.getData()));
		}
		
		return true;
	}

	@Override
	protected boolean doUnregister(String path) throws Exception {
		client.delete().forPath(path);
		return true;
	}

	@Override
	protected boolean doSetNode(String path, Node node) throws Exception {
		if(node==null) {
			client.setData().forPath(path,ArrayUtils.EMPTY_BYTE_ARRAY);
		}
		else {
			client.setData().forPath(path,doByteSerialize(node.getData()));
		}
		
		return true;
	}

	@Override
	protected Node doGetNode(String path) throws Exception {
		byte bytes[]=client.getData().forPath(path);
		if(ArrayUtils.isEmpty(bytes)) {
			return null;
		}
		
		return new Node(doByteDeserialize(bytes));
	}

	@Override
	protected Collection<Node> doGetNodes(String path) throws Exception {
		List<String> children=client.getChildren().forPath(path);
		if(CollectionUtils.isEmpty(children)) {
			return Collections.emptyList();
		}
		
		Collection<Node> result=new ArrayList<Node>();
		
		for(String node:children) {
			result.add(new Node(node,null,null));
		}
		
		return result;
	}

	@Override
	protected boolean doIsExist(String path) throws Exception {
		try {
			return client.checkExists().forPath(path)!=null;
		}
		catch(NoNodeException e) {
			return false;
		}
	}

	@Override
	protected boolean doListen(String path, Listener listener) throws Exception {
		return watcher.listen(path, listener);
	}

	@Override
	protected boolean doUnlisten(String path, Listener listener) throws Exception {
		return watcher.unlisten(path, listener);
	}

	@Override
	protected boolean doSelectLeader(String path, int timeout, Listener listener) throws Exception {
		LeaderLatch leaderLatch=new LeaderLatch(client,path);
		leaderLatch.start();
		leaderLatch.await(timeout, TimeUnit.MILLISECONDS);
		
		try {
			if(leaderLatch.hasLeadership()) {
				listener.onListen(path);
			}
		}
		finally {
			leaderLatch.close();
		}
		return true;
	}
	
	protected CreateMode getNodeCreateMode(Node node) {
		NodeMode mode=getNodeMode(node);
		switch (mode) {
			case PERSISTENT:{
				return CreateMode.PERSISTENT;
			}
			case EPHEMERAL: {
				return CreateMode.EPHEMERAL;
			}
		}
		return null;
	}
	
	public void setClient(CuratorFramework client) {
		this.client = client;
	}
	public CuratorFramework getClient() {
		return client;
	}
	public void setConfig(RegistryConfig config) {
		this.config = config;
	}
	public RegistryConfig getConfig() {
		return config;
	}
}